package com.nova.bluetooth.ui.ai.translate;


import static com.nova.bluetooth.base.CommonMessageWrap.ACTION_AIUI_TTS_RESULT;
import static com.nova.bluetooth.xunFeiSDK.engine.EngineConstants.RECORDER_DATA;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Typeface;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.style.StyleSpan;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;

import androidx.activity.EdgeToEdge;
import androidx.activity.OnBackPressedCallback;
import androidx.annotation.NonNull;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.iflytek.aiui.AIUIConstant;
import com.iflytek.aiui.AIUIEvent;
import com.nova.bluetooth.MyApp;
import com.nova.bluetooth.R;
import com.nova.bluetooth.base.CommonMessageWrap;
import com.nova.bluetooth.base.CommonResult;
import com.nova.bluetooth.base.TranslatingBean;
import com.nova.bluetooth.databinding.ActivityFaceTranslateBinding;
import com.nova.bluetooth.helpUtils.AppUtil;
import com.nova.bluetooth.helpUtils.DateUtil;
import com.nova.bluetooth.helpUtils.EventBusUtil;
import com.nova.bluetooth.helpUtils.LogUtil;
import com.nova.bluetooth.helpUtils.NetworkUtil;
import com.nova.bluetooth.helpUtils.OnClickEvent;
import com.nova.bluetooth.helpUtils.StorageUtil;
import com.nova.bluetooth.helpUtils.ToastUtils;
import com.nova.bluetooth.netWork.NetConstant;
import com.nova.bluetooth.permission.OnPermissionListener;
import com.nova.bluetooth.permission.PermissionManageActivity;
import com.nova.bluetooth.permission.PermissionType;
import com.nova.bluetooth.ui.ai.MyAiUiViewModel;
import com.nova.bluetooth.webIat.WebXunFeiTWS;
import com.nova.bluetooth.xunFeiSDK.engine.AiuiEngine;
import com.nova.bluetooth.xunFeiSDK.engine.EngineConstants;
import com.nova.bluetooth.xunFeiSDK.recorder.SystemRecorder;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.lang.ref.WeakReference;
import java.util.List;
import java.util.Objects;

public class FaceTranslateActivity extends PermissionManageActivity implements
        MyAiUiViewModel.OnAiUiRecognizeListener, WebXunFeiTWS.OnIATWSRecognizeListener {
    /***************************SCO连接 start****************************/
    private void setupBluetooth() {
        // TODO: 2024/2/27 不采用SCO连接，使用手机MIC录音, DoNothing

//        // 开启蓝牙采集音频
//        AudioManager manager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
//        manager.setBluetoothScoOn(true);
//        manager.startBluetoothSco();
    }

    private void stopBluetoothSco() {
//        // 停止蓝牙音频采集并注销广播接收器
//        AudioManager manager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
//        manager.setBluetoothScoOn(false);
//        manager.stopBluetoothSco();
    }

    private void registerSCOReceiver() {
        // 注册蓝牙状态广播接收器
        IntentFilter filter = new IntentFilter();
        filter.addAction(AudioManager.ACTION_SCO_AUDIO_STATE_UPDATED);
        registerReceiver(bluetoothStateReceiver, filter);
    }

    private void unregisterSCOReceiver() {
        unregisterReceiver(bluetoothStateReceiver);
    }

    private final BroadcastReceiver bluetoothStateReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (AudioManager.ACTION_SCO_AUDIO_STATE_UPDATED.equals(intent.getAction())) {
                int state = intent.getIntExtra(AudioManager.EXTRA_SCO_AUDIO_STATE, -1);
                if (state == AudioManager.SCO_AUDIO_STATE_CONNECTED) {
                    // 蓝牙耳机已连接，可以进行音频采集了
                } else if (state == AudioManager.SCO_AUDIO_STATE_DISCONNECTED) {
                    // 蓝牙耳机断开连接，需要处理相应逻辑
                }
            }
        }
    };

    /***************************end****************************/

    /**
     * 检查耳机|高亮显示已连接
     *
     * @param textView 需要显示文本的 TextView
     * @param text     需要处理的字符串
     */
    public void highlightText(TextView textView, String text) {
        // 检查输入字符串是否为空
        if (text == null || text.isEmpty()) {
            return;
        }

        // 使用 "|" 分隔字符串
        String[] parts = text.split("\\|");

        // 检查分隔后的数组长度
        if (parts.length != 2) {
            textView.setText(text);
            return;
        }

        // 获取前半部分和后半部分字符串
        String part1 = parts[0].trim();
        String part2 = parts[1].trim();


        SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(part1 + " " + part2);
        // 设置 str2 部分为加粗
        spannableStringBuilder.setSpan(new StyleSpan(Typeface.BOLD),
                part1.length() + 1,
                part1.length() + part2.length() + 1,
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

//        // 设置 str2 部分为红色
//        spannableStringBuilder.setSpan(new ForegroundColorSpan(Color.RED),
//                part1.length() + 1,
//                part1.length() + part2.length() + 1,
//                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

        // 设置到 TextView 中
        textView.setText(spannableStringBuilder);
    }


    private final boolean DEF_LEFT_EAR_IN_TOP = true;  //默认耳机左耳切换对应顶部View
    public static int IsAiTranslateActivityTag = 1;

    private MyAiUiViewModel aiUiViewModel;
    private WebXunFeiTWS webIATWSManage;
    private MyHandler myHandler;

    private String translatingString = ""; //送去翻译的翻译源

    private static class MyHandler extends Handler {
        public static final int WAVE_AMPLITUDE_TAG = 0x01;
        public static final int TRANSLATE_BAIDU_TAG = 0x02;
        public static final int SEND_END_DATA_TAG = 0x04;
        public static final int TIMER_TAG = 0x03;
        FaceTranslateActivity activity;

        public MyHandler(WeakReference<FaceTranslateActivity> weakReference) {
            activity = weakReference.get();
        }

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case WAVE_AMPLITUDE_TAG:
//                    activity.binding.waveViewBottom.setWaveAmplitude(activity.waveAmplitude);
//                    activity.binding.waveViewTop.setWaveAmplitude(activity.waveAmplitude);
                    break;
                case TRANSLATE_BAIDU_TAG:
                    TranslatingBean lastBean = activity.viewModel.getLastTranslatingBean();
                    activity.translatingString = lastBean.getOriginalContent();
                    activity.viewModel.baiduTranslation(
                            lastBean.getOriginalContent(),
                            Objects.requireNonNull(activity.translateLanguageCode));
                    //利用完了，清空识别消息
                    activity.aiUiViewModel.clearRecognitionText();

                    activity.scrollToBottom();
                    break;
                case SEND_END_DATA_TAG:
                    activity.webIATWSManage.sendEndData();
                    break;
                case TIMER_TAG:
                    activity.updateTimer();
                    break;
            }
        }
    }

    private Thread senderThread;
    private int threadAmplitude = 10;
    private boolean isSending = false; // 标志变量，用于控制线程是否继续发送
    public final static int SEND_DATA_TIME_INTERVAL = 30; // 每条数据的发送间隔-++++++

    public synchronized void setAmplitude(int amplitude) {
        if (amplitude < 5) amplitude = 5;
        if (amplitude > 25) amplitude = 25;
        threadAmplitude = amplitude;
//        LogUtil.d("threadAmplitude:" + threadAmplitude);
        // 如果senderThread不存在，创建新线程
        if (senderThread == null) {
            startSending();
        }
    }

    public synchronized void startSending() {
        if (senderThread == null) {
            isSending = true; // 启动发送标志
            senderThread = new Thread(() -> {
                while (isSending) { // 使用标志变量控制线程运行
                    if (waveAmplitude > threadAmplitude) {
                        waveAmplitude--;
                        myHandler.sendEmptyMessage(MyHandler.WAVE_AMPLITUDE_TAG);
                    } else if (waveAmplitude < threadAmplitude) {
                        waveAmplitude++;
                        myHandler.sendEmptyMessage(MyHandler.WAVE_AMPLITUDE_TAG);
                    }
                    try {
                        Thread.sleep(SEND_DATA_TIME_INTERVAL); // 每隔Nms发送一次
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
            senderThread.start();
        }
    }

    public synchronized void stopSending() {
        isSending = false; // 设置标志变量为false，使线程退出循环
        senderThread = null; // 将线程置空，以便下次可以重新启动
    }

    private ActivityFaceTranslateBinding binding;
    private MyTranslateViewModel viewModel;


    /**********************************网络检测计时**************************************/
    private boolean isTimerRunning = false;
    private int seconds = 0;

    private void startTimer() {
        if (!isTimerRunning) {
            isTimerRunning = true;
            myHandler.postDelayed(timerRunnable, 1000);
        }
    }

    private void pauseTimer() {
        if (isTimerRunning) {
            isTimerRunning = false;
            myHandler.removeCallbacks(timerRunnable);
        }
    }

    private void updateTimer() {
        seconds++;
        String currentProgress = DateUtil.getDateToString(seconds * 1000, DateUtil.H_M_S, "UTC");
        myHandler.postDelayed(timerRunnable, 1000);
    }

    private final Runnable timerRunnable = new Runnable() {
        @Override
        public void run() {
            myHandler.sendEmptyMessage(MyHandler.TIMER_TAG);
            checkNet();
        }
    };

    private int times_tag = 0;

    private void checkNet() {
        new Thread(() -> {
            String hostUrl_def = "iat-api.xfyun.cn";
            long error_time = NetworkUtil.getPingTime(hostUrl_def);
            LogUtil.i("test===>网络延时检测：" + error_time);
            if (error_time > 150) {
                times_tag++;
            }

            if (times_tag > 5) {
                binding.getRoot().post(() -> ToastUtils.show("网络异常"));
                times_tag = 0;
            }
        }).start();
    }

    private int waveAmplitude = 5;

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessage(CommonMessageWrap message) {
        switch (message.getEventCode()) {
            case ACTION_AIUI_TTS_RESULT:
                AIUIEvent aiuiEvent = (AIUIEvent) message.getObject();
                if (aiuiEvent.eventType == AIUIConstant.CMD_STOP_SAVE) {
                    if (aiuiEvent.arg1 == 5) { //语音合成完毕
                        MyAiUiViewModel.TTSIsStart = false;
                        LogUtil.d("TTS 播放完毕");

                        if (!AppUtil.isForeground(this)) {
                            return;
                        }

                        //重新打开录音
                        if (!isRecording) {
                            showPermissionRequiresDialog();
                        }
                    }
                }
                break;

            case RECORDER_DATA:
                byte[] audioData = (byte[]) message.getObject();
                break;
        }
    }

    private long activityOnLineTime;  //记录启动界面时间

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        activityOnLineTime = System.currentTimeMillis();
        EventBusUtil.register(this);
        //屏幕常亮
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        initBinding();
        setContentView(binding.getRoot());
        initView();
        initData();
        observe();
        myHandler = new MyHandler(new WeakReference<>(FaceTranslateActivity.this));
        getOnBackPressedDispatcher().addCallback(this, callback);
        initRecordPath();

//        showPermissionRequiresOnlyDialog();
        registerSCOReceiver();

        AiuiEngine.setAiuiEngineOpen = false;
        mBinding = binding;
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (IsAiTranslateActivityTag == -1) {  //重置，防别的模块数据干扰
            initRecordPath();
            deleteUnUserAudioFile();
            aiUiViewModel.clearRecognitionText();
            IsAiTranslateActivityTag = 1;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBusUtil.unRegister(this);
        aiUiViewModel.setOnAiUiRecognizeListenerAndClear(null);
        aiUiViewModel.destroyAiUiAllEngine();
        webIATWSManage.onDestroy();

        myHandler.removeCallbacksAndMessages(null);

        //如果正在TTS中，停止他
        stopTTS();
        stopSending();

        deleteUnUserAudioFile();

        //取消屏幕常亮
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        stopBluetoothSco();
        unregisterSCOReceiver();

        AiuiEngine.setAiuiEngineOpen = true;
    }


    OnBackPressedCallback callback = new OnBackPressedCallback(true) {
        @Override
        public void handleOnBackPressed() {
            // 在这里处理返回键按下的逻辑
            // 如果要拦截返回键，可以在这里添加你的逻辑，否则调用 isEnabled() 方法检查是否应该交给默认行为
            if (isEnabled()) {
                finish();
                // 处理返回键按下的逻辑
                // 例如，你可以在这里执行一些操作，然后调用 finish() 关闭 Activity
//                showUserBackTipsDialog();
            }
        }
    };

    private void deleteUnUserAudioFile() {
        File unUserFile = new File(SystemRecorder.saveRecordPath);
        if (unUserFile.exists()) {
            unUserFile.delete();
            SystemRecorder.saveRecordAudioTimeSnippet = 0;
        }
    }

    private TranslateAdapter topAdapter;
    private TranslateAdapter bottomAdapter;

    private void initBinding() {
        binding = ActivityFaceTranslateBinding.inflate(getLayoutInflater());
        viewModel = new ViewModelProvider(this).get(MyTranslateViewModel.class);
        aiUiViewModel = new ViewModelProvider(MyApp.getInstance()).get(MyAiUiViewModel.class);

        viewModel.enableRefresh.set(false);
        binding.setVm(viewModel);
        binding.setLifecycleOwner(this);
        binding.setTopLayoutManager(new LinearLayoutManager(this));
        binding.setBottomLayoutManager(new LinearLayoutManager(this));
        topAdapter = new TranslateAdapter();
        topAdapter.adapterTypeIsBottom(false);
        bottomAdapter = new TranslateAdapter();
        bottomAdapter.adapterTypeIsBottom(true);
        binding.setTopAdapter(topAdapter);
        binding.setBottomAdapter(bottomAdapter);
        MyOnClickEvent myOnClickEvent = new MyOnClickEvent();
        binding.setOnClick(myOnClickEvent);
//        binding.ivSwitch.setOnClickListener(new OnClickEvent() {
//            @Override
//            public void singleClick(View v) {
//                myOnClickEvent.singleClick(v);
//            }
//        });
    }

    private void initView() {
        aiUiViewModel.initSDK(this);
        aiUiViewModel.setOnAiUiRecognizeListenerAndClear(this);
        webIATWSManage = WebXunFeiTWS.getInstance();
        webIATWSManage.clearDiscard();
        webIATWSManage.setOnIATWSRecognizeListener(this);

        viewModel.isBottomWaveViewVisible.setValue(false);
        viewModel.isTipsVisible.setValue(true);
        updateSwitchLanguageUI();
    }

    private void setSpeakingUI(boolean isBottomView) {
        boolean isTranslating = Boolean.TRUE.equals(viewModel.isTranslating.getValue());
        if (isTranslating) {
            ToastUtils.show("正在录音，请稍后再试");
            return;
        }

        if (!isRecording) {
            showPermissionRequiresDialog();
        }

        viewModel.bottomIsAsrSpeaking.setValue(isBottomView);

        resetBottomAndTopUI(isBottomView);
        resetSpeakingLanguage();

        speakingTTSTipsVoice();
    }

    boolean isStartFromDevice = false;  //是否通话录音设备支持  用户可能从首页进来的，
    // 一些和设备支持功能要做区分，比如支持对耳翻译的设备进入到翻译界面是不可点击APP界面切换UI的，通过设备操作，
    // 但从主页进来的话，需要可以点击APP界面切换UI

    private void initData() {
    }

    private void observe() {
        viewModel.isTipsVisible.observe(this, new Observer<Boolean>() {
            @Override
            public void onChanged(Boolean aBoolean) {
                if (!aBoolean) {
                    showPermissionRequiresDialog();
                }
            }
        });
        viewModel.getTextTranslateResultData().observe(this, textTranslateResult -> {
            textTranslateResult.getData();
        });

        viewModel.baiduTranslationResult.observe(this, textTranslateResult -> {
            if (Objects.equals(textTranslateResult.getCode(), NetConstant.NETWORK_RESULT_OK)) {
                scrollToBottom();
                translateContextTTS(textTranslateResult.getData());
                SystemRecorder.resetSaveRecordAudioTime = 1;  //重置，录音时间标识计算
            }
        });
        viewModel.insertTranslationContentResult.observe(this, new Observer<CommonResult>() {
            @Override
            public void onChanged(CommonResult commonResult) {
                if (commonResult != null) {
                    ToastUtils.show("上传成功");
                    finish();
                }
            }
        });
    }

    private void updateSelectedLangUI(List<LanguageSelectBean> dataList) {
        mLeftLanguageName = dataList.get(0).getLanguageName();
        mRightLanguageName = dataList.get(1).getLanguageName();

        setLangText();

        String topString = getTipsByLanguage(DEF_LEFT_EAR_IN_TOP ? mLeftLanguageName : mRightLanguageName, false);
        String bottomString = getTipsByLanguage(DEF_LEFT_EAR_IN_TOP ? mRightLanguageName : mLeftLanguageName, true);

        binding.tvTopTips.setText(topString);
        binding.tvBottomTips.setText(bottomString);
    }

    private void setLangText() {
        binding.tvLanguageRight.setText(mRightLanguageName);
        binding.tvLanguageLeft.setText(mLeftLanguageName);

        binding.tvTopLang.setText(DEF_LEFT_EAR_IN_TOP ? mLeftLanguageName : mRightLanguageName);
        binding.tvBottomLang.setText(DEF_LEFT_EAR_IN_TOP ? mRightLanguageName : mLeftLanguageName);
    }

    private boolean isgDeviceSpeakTranslationMode() {
        return true;
    }



    private void setTipsViewVisible(boolean isBottom) {
        viewModel.isTipsVisible.setValue(false);
        viewModel.isSwitchLanguageVisible.setValue(false);
        resetBottomAndTopUI(isBottom);
        initTopView();

        viewModel.bottomIsAsrSpeaking.setValue(isBottom);
        resetSpeakingLanguage();
        updateSwitchLanguageUI();
    }

    private void resetBottomAndTopUI(boolean isBottom) {
        if (isBottom) {
            viewModel.isTopLangTipsVisible.setValue(false);
            viewModel.isBottomLangTipsVisible.setValue(true);
            viewModel.isBottomWaveViewVisible.setValue(true);
            topAdapter.resetTextColorByUser(false);
            bottomAdapter.resetTextColorByUser(true);
        } else {
            viewModel.isTopLangTipsVisible.setValue(true);
            viewModel.isBottomLangTipsVisible.setValue(false);
            viewModel.isBottomWaveViewVisible.setValue(false);
            topAdapter.resetTextColorByUser(true);
            bottomAdapter.resetTextColorByUser(false);
        }
    }

    private void resetSpeakingLanguage() {
        setAsrAndTranslateLanguageCode();
        resetSpeakingScene();
    }

    /**
     * 设置语音识别语言
     */
    private void resetSpeakingScene() {
//        if (asrLanguageCode.contains("cn")) {
//            aiUiViewModel.setScene(true);
//        } else if (asrLanguageCode.contains("en")) {
//            aiUiViewModel.setScene(false);
//        }
        LogUtil.d("test==>设置识别语言：" + " asrLanguageCode " + asrLanguageCode +
                " asrLanguageAccentCode " + asrLanguageAccentCode +
                " asrLanguageAccentType " + asrLanguageAccentType);
        webIATWSManage.setScene(asrLanguageCode, asrLanguageAccentCode, asrLanguageAccentType);
    }

    private String asrLanguage = "cn";

    private void setScene(String lang) {
//        if (asrLanguage.equals("cn")) {
//            aiUiViewModel.setScene(true);
//        } else {
//            aiUiViewModel.setScene(false);
//        }

//        webIATWSManage.setScene(lang);
    }

    private void initTopView() {
        if (angle % 360 != 0) {
            angle = angle + 180f;
            flipView(binding.topView);
        }
    }

    private float angle = 0;

    /**
     * 旋转动画
     *
     * @param view
     */
    private void flipView(View view) {
        // 创建ObjectAnimator对象
        // 参数1：要进行动画的对象
        // 参数2：要进行动画的属性名（这里是旋转动画，所以属性名是"rotation"）
        // 参数3：旋转的起始角度
        // 参数4：旋转的结束角度
        ObjectAnimator objectAnimator = ObjectAnimator.ofFloat(view, "rotation", angle, angle - 180f);
        // 设置动画的时长（单位：毫秒）
        objectAnimator.setDuration(800);
        // 开始动画
        objectAnimator.start();
        angle = angle - 180f;
    }

    /**
     * 淡入效果
     */
    private void fadeInAnimator(View view) {
        // 创建一个淡入动画
        ObjectAnimator fadeInAnimator = ObjectAnimator.ofFloat(view, "alpha", 0.0f, 1.0f);
        fadeInAnimator.setDuration(800);
        fadeInAnimator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationStart(Animator animation) {
                viewModel.isSwitchLanguageVisible.setValue(true);
            }
        });
        fadeInAnimator.start();
    }

    /**
     * 淡出效果
     *
     * @param view
     */
    private void fadeOutAnimator(View view) {
        ObjectAnimator fadeOut = ObjectAnimator.ofFloat(view, "alpha", 1.0f, 0.0f);
        fadeOut.setDuration(800);
        // 设置动画结束后将 View 设为隐藏
        fadeOut.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                viewModel.isSwitchLanguageVisible.setValue(false);
            }
        });
        fadeOut.start();
    }


    /*******************************语言选择弹窗*********************************/
    private String mLeftLanguageName = "普通话";
    private String mRightLanguageName = "英语";

    private String asrLanguageCode = "zh_cn";
    private String translateLanguageCode = "en";


    private int asrLanguageAccentType = 1;//1语言 2方言
    private String asrLanguageAccentCode = "mandarin";
    public static final int SHOW_ASR_LANGUAGE_DIALOG = 0x01;
    public static final int SHOW_TRANSLATE_LANGUAGE_DIALOG = 0x02;
    private boolean isShowLanguageDialogLeft = true;


    private void setAsrAndTranslateLanguageCode() {
        boolean bottomIsSpeaking = Boolean.TRUE.equals(viewModel.bottomIsAsrSpeaking.getValue());
        LanguageSelectBean mAsrLanguageBean;
        if (bottomIsSpeaking) {
            mAsrLanguageBean = NovaTransformLanguageCodeUtil.getAsrLanguageBeanByTranslateName(
                    DEF_LEFT_EAR_IN_TOP ? mRightLanguageName : mLeftLanguageName);
            asrLanguageCode = mAsrLanguageBean.getLanguageCode();
            translateLanguageCode = NovaTransformLanguageCodeUtil.getTranslateBeanByAsrLanguageName(
                    DEF_LEFT_EAR_IN_TOP ? mLeftLanguageName : mRightLanguageName).getLanguageCode();
        } else {
            mAsrLanguageBean = NovaTransformLanguageCodeUtil.getAsrLanguageBeanByTranslateName(
                    DEF_LEFT_EAR_IN_TOP ? mLeftLanguageName : mRightLanguageName);
            asrLanguageCode = mAsrLanguageBean.getLanguageCode();
            translateLanguageCode = NovaTransformLanguageCodeUtil.getTranslateBeanByAsrLanguageName(
                    DEF_LEFT_EAR_IN_TOP ? mRightLanguageName : mLeftLanguageName).getLanguageCode();
        }

        asrLanguageAccentType = mAsrLanguageBean.getType();
        if (asrLanguageAccentType == 2) {
            asrLanguageAccentCode = mAsrLanguageBean.getLanguageCode();
        } else {
            asrLanguageAccentCode = "mandarin";
        }

        viewModel.asrTargetLanguage.setValue(asrLanguageCode);
        viewModel.translationTargetLanguage.setValue(translateLanguageCode);
    }

    private void switchLanguageType() {
        //切换语言
        String switchLanguageName = mRightLanguageName;
        mRightLanguageName = mLeftLanguageName;
        mLeftLanguageName = switchLanguageName;

        translateLanguageCode = NovaTransformLanguageCodeUtil.
                getTranslateBeanByAsrLanguageName(mRightLanguageName).getLanguageCode();

        LanguageSelectBean asrLanguageSelectBean = NovaTransformLanguageCodeUtil.getAsrLanguageBeanByTranslateName(mLeftLanguageName);
        asrLanguageCode = asrLanguageSelectBean.getLanguageCode();
        asrLanguageAccentType = asrLanguageSelectBean.getType();
        asrLanguageAccentCode = asrLanguageSelectBean.getLanguageCode();
    }

    private void updateSwitchLanguageUI() {
        String topString = getTipsByLanguage(DEF_LEFT_EAR_IN_TOP ? mLeftLanguageName : mRightLanguageName, false);
        String bottomString = getTipsByLanguage(DEF_LEFT_EAR_IN_TOP ? mRightLanguageName : mLeftLanguageName, true);
        binding.tvTopTips.setText(topString);
        binding.tvBottomTips.setText(bottomString);

        binding.ivTopPic.setImageResource(R.drawable.ic_translate_ear_mic);
        binding.ivBottomPic.setImageResource(R.drawable.ic_translate_ear_mic);
        setLangText();
    }

    private String getTipsByLanguage(String languageName, boolean isBottom) {
        String tip = "";
        if (isgDeviceSpeakTranslationMode()) {
            if (DEF_LEFT_EAR_IN_TOP) {
                tip = isBottom ? "长按右边耳机说" : "长按左边耳机说";
            } else {
                tip = isBottom ? "长按左边耳机说" : "长按右边耳机说";
            }

        } else {
            tip = "点击这里说";
        }
        return tip + " " + languageName;
    }


    private void scrollToBottom() {
        binding.recyTop.smoothScrollToPosition(topAdapter.getItemCount());
        binding.recyBottom.smoothScrollToPosition(bottomAdapter.getItemCount());
    }

    private void translateContextTTS(String str) {
        if (Boolean.TRUE.equals(viewModel.ttsIsOpen.getValue())) {
            if (!isgDeviceSpeakTranslationMode()) {
                stopRecord(); //先停止录音，避免把TTS合成的声音也录进去 (手机模式才回有此问题)
            }

            String translateLanguageName = NovaTransformLanguageCodeUtil.getLanguageNameByCode(false, translateLanguageCode);
            String ttsRobot = NovaTransformLanguageCodeUtil.getTranslateBeanByTranslateLanguageName(translateLanguageName).getSpeakerCode();
            MyAiUiViewModel.TTS_ROBOT = ttsRobot;
            aiUiViewModel.startTTSBySdk(str);
        }
    }

    /**
     * 播报提示音
     */
    private void speakingTTSTipsVoice() {
        String asrLanguageName = NovaTransformLanguageCodeUtil.getLanguageNameByCode(true, asrLanguageCode);
        //翻译语言才有SpeakerCode
        LanguageSelectBean translateLanguageBean = NovaTransformLanguageCodeUtil.getTranslateBeanByAsrLanguageName(asrLanguageName);
        String ttsRobot = translateLanguageBean.getSpeakerCode();
        MyAiUiViewModel.TTS_ROBOT = ttsRobot;
        aiUiViewModel.startTTSBySdk(translateLanguageBean.getBroadcastContent());
    }


    private void stopTTS() {
        if (Boolean.TRUE.equals(viewModel.ttsIsOpen.getValue())) {
            aiUiViewModel.stopTTS();
        }
    }

    /******************************权限管理******************************/


    private void showPermissionRequiresDialog() {
        getRecordAudioPermission(new OnPermissionListener() {
            @Override
            public void onPermissionGranted(PermissionType permissionType) {
                initAiUiRecord();
            }

            @Override
            public void onPermissionDenied(PermissionType permissionType) {

            }
        }, "获取录音权限用于语音识别");

    }


    private void requiresAIUIAndRecordPermission() {
        getAIUIRecordPermission(new OnPermissionListener() {
            @Override
            public void onPermissionGranted(PermissionType permissionType) {
                //权限都有了
                initAiUiRecord();
            }

            @Override
            public void onPermissionDenied(PermissionType permissionType) {

            }
        }, "获取录音权限用于语音识别");
    }


    /**
     * 启动应用的设置
     *
     * @since 2.5.0
     */
    private void startAppSettings() {
        Intent intent = new Intent(
                Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.parse("package:" + getPackageName()));
        startActivity(intent);
    }

    /********************************Web语音识别**********************************/
    @Override
    public void onWebAsrResult(String result, int status) {
        binding.getRoot().post(() -> {
            if (IsAiTranslateActivityTag == -1) {
                return;
            }
            LogUtil.i(TAG + "识别结果展示-status onAsrResult：" + result);
//            viewModel.isLanguageTipsVisible.setValue(false);

            if (isgDeviceSpeakTranslationMode()) {  //有新的内容出来就停止前面的语音合成
                //优先录音识别，如果有在tts 就停了他
                stopTTS();
            }

            List<TranslatingBean> list = viewModel.translatingBeanList.getValue();
            assert list != null;
            if (list.size() > 0) {
                list.get(list.size() - 1).setOriginalContent(result);
            } else {
                TranslatingBean translatingBean = new TranslatingBean();
                translatingBean.setOriginalContent(result);
                list.add(translatingBean);
            }

            viewModel.setContentToTargetList(
                    result,
                    "");
            scrollToBottom();

            myHandler.removeMessages(MyHandler.SEND_END_DATA_TAG);
            myHandler.removeMessages(MyHandler.TRANSLATE_BAIDU_TAG);
            if (status == 2) {
                myHandler.sendEmptyMessage(MyHandler.TRANSLATE_BAIDU_TAG);
            } else {
                myHandler.sendEmptyMessageDelayed(MyHandler.SEND_END_DATA_TAG, 3200);
                //超过n秒没新内容就去翻译,防止卡在那不动
                myHandler.sendEmptyMessageDelayed(MyHandler.TRANSLATE_BAIDU_TAG, 4000);
            }
        });
    }

    @Override
    public void onWebRecordStatus(boolean recording) {
        isRecording = recording;
    }

    @Override
    public void onWebStartSpeaking() {
        viewModel.isTranslating.postValue(true);  //有识别结果，令APP进入翻译中状态
    }

    /******************************* AIUI 语音助手结果监听******************************/

    private boolean isRecording = false;

    private void initAiUiRecord() {
        //打开录音数据保存开关
        EngineConstants.saveAudio = true;

        //启动语音听写接口识别
        webIATWSManage.runWebIATWSWebSocket();

        //初始化录音(唤醒直接识别)
        aiUiViewModel.initRecorder();

    }

    private void initRecordPath() {
        String suffix = "pcm";
        String fileName = "Ai_Translate_Recorder" + "." + suffix;
        String opusFile = "Ai_Translate_Recorder.opus";

        String audioDir = StorageUtil.getAudioDir();
        File musicDir = new File(audioDir);

        File file = new File(musicDir, "/" + fileName); //文件夹路径 + 文件名
        File mOpusFile = new File(musicDir, "/" + opusFile);

        SystemRecorder.saveRecordPath = file.getAbsolutePath(); //设置录音文件路径存放录音
        SystemRecorder.saveRecordAudioTimeSnippet = 0; //初始化，时间记录TAG为0
        SystemRecorder.mMultiple = SystemRecorder.IAT_MULTIPLE;

        startTimer();
    }

    private void stopRecordAndRecognize() {
        //关闭录音数据保存开关
        EngineConstants.saveAudio = false;

        aiUiViewModel.clearRecognitionText();
        stopRecord();
    }

    private void stopRecord() {
        aiUiViewModel.stopRecord();
        webIATWSManage.stopWebSocketThread();
    }

    @Override
    public void onStartSpeaking() {
        viewModel.isTranslating.setValue(true);  //有识别结果，令APP进入翻译中状态
    }

    @Override
    public void onAsrResult(String result) {
        if (IsAiTranslateActivityTag == -1) {
            return;
        }
        LogUtil.i(TAG + "识别结果展示 onAsrResult：" + result);

        if (isgDeviceSpeakTranslationMode()) {  //有新的内容出来就停止前面的语音合成
            //优先录音识别，如果有在tts 就停了他
            stopTTS();
        }

        //超过n秒没新内容就去翻译
        myHandler.removeMessages(MyHandler.TRANSLATE_BAIDU_TAG);
        myHandler.sendEmptyMessageDelayed(MyHandler.TRANSLATE_BAIDU_TAG, 2000);

        List<TranslatingBean> list = viewModel.translatingBeanList.getValue();
        assert list != null;
        if (list.size() > 0) {
            list.get(list.size() - 1).setOriginalContent(result);
        } else {
            TranslatingBean translatingBean = new TranslatingBean();
            translatingBean.setOriginalContent(result);
            list.add(translatingBean);
        }
        viewModel.setContentToTargetList(
                result,
                "");
        scrollToBottom();
    }

    @Override
    public void onAsrNoSplicingResult(String result) {
        LogUtil.i(TAG + "识别结果展示：" + result);

//        List<TranslatingBean> list = viewModel.translatingBeanList.getValue();
//        assert list != null;
//        if (list.size() > 0) {
//            list.get(list.size() - 1).setOriginalContent(result);
//        } else {
//            TranslatingBean translatingBean = new TranslatingBean();
//            translatingBean.setOriginalContent(result);
//            list.add(translatingBean);
//        }
//        viewModel.setContentToTargetList(Objects.requireNonNull(viewModel.bottomLanguageType.getValue()),
//                viewModel.translationTargetLanguage.getValue(), true, result);
//        scrollToBottom();
    }

    @Override
    public void onAsrNoSplicingResultEnd(boolean isResultEnd) {
        if (isResultEnd) {
//            ToastUtils.show("识别结束");
            LogUtil.i(TAG + "onAsrNoSplicingResultEnd：" + isResultEnd);

//            TranslatingBean lastBean = viewModel.getLastTranslatingBean();
//            viewModel.baiduTranslation(
//                    lastBean.getOriginalContent(),
//                    Objects.requireNonNull(viewModel.translationTargetLanguage.getValue()));
//
//            scrollToBottom();
        }
    }

    @Override
    public void onRecordStatus(boolean recording) {
        isRecording = recording;
    }

    /****************************耳机端操作*******************************/
    //a5ffff00
    private void dealWithDeviceNotifyData(byte[] data) {
        if (data[1] == (byte) 0xff && data[2] == (byte) 0xff) {
            switch (data[3]) {
                case (byte) 0x00:
                    if (viewModel.isTipsVisible.getValue()) {
                        setTipsViewVisible(true);
                    }
                    setSpeakingUI(false);
                    LogUtil.d("test==>耳机触发左耳推送数据中...");
                    break;
                case (byte) 0x01:
                    if (viewModel.isTipsVisible.getValue()) {
                        setTipsViewVisible(false);
                    }
                    setSpeakingUI(true);
                    LogUtil.d("test==>耳机触发右耳推送数据中...");
                    break;
            }
        }

    }



    public class MyOnClickEvent extends OnClickEvent {
        @Override
        public void singleClick(View v) {
            int id = v.getId();

            if (id == R.id.iv_back) {
                finish();
            } else if (id == R.id.iv_switch) {
                if (Boolean.TRUE.equals(viewModel.isTipsVisible.getValue())) {
                    flipView(binding.topTipsView);

                    if (binding.llLanguageTag.getVisibility() == View.VISIBLE) {
                        fadeOutAnimator(binding.llLanguageTag);
                    } else {
                        fadeInAnimator(binding.llLanguageTag);
                    }
                } else {
                    flipView(binding.topView);
                }
            } else if (id == R.id.shadow_switch_language) {
                switchLanguageType();
                updateSwitchLanguageUI();
            } else if (id == R.id.iv_tts_switch) {
//                boolean isOpen = viewModel.ttsIsOpen.getValue();
//                viewModel.ttsIsOpen.setValue(!isOpen);
            }else if (id == R.id.linearLayoutTop || id == R.id.top_click_view){
                if (viewModel.isTipsVisible.getValue()) {
                    setTipsViewVisible(true);
                }
                setSpeakingUI(false);
            }else if ( id == R.id.linearLayoutBottom ||  id == R.id.bottom_click_view){
                if (viewModel.isTipsVisible.getValue()) {
                    setTipsViewVisible(false);
                }
                setSpeakingUI(true);
            }
        }
    }
}